// 页面加载完成后执行
window.onload = () => {
    // 从本地存储获取监控到的请求
    chrome.storage.local.get(['monitoredRequests'], result => {
        const requests = result.monitoredRequests || [];
        const container = document.getElementById('requests');

        // 如果没有捕获到请求，显示提示信息
        if (requests.length === 0) {
            container.innerHTML = '<p>没有捕获到任何请求。</p>';
            return;
        }

        // 清空旧内容
        container.innerHTML = '';

        // 遍历每个请求，创建展示内容
        requests.forEach(req => {
            const div = document.createElement('div');
            div.className = 'request';

            // 创建基本内容
            div.innerHTML = `
        <strong>方法:</strong> ${req.method}<br>
        <strong>URL:</strong> ${req.url}<br>
        <strong>时间:</strong> ${req.time}<br>
        <strong>请求头:</strong><pre>${formatHeaders(req.headers)}</pre>
      `;

            // 创建按钮
            const button = document.createElement('button');
            button.textContent = '重新发送';
            button.className = 'resend-button';

            // 添加点击事件
            button.addEventListener('click', () => {
                resendRequest(button, req.url, req.method);
            });

            // 创建响应展示区域
            const responseContainer = document.createElement('div');
            responseContainer.className = 'response-container';

            // 插入元素
            div.appendChild(button);
            div.appendChild(responseContainer);

            // 添加到页面
            container.appendChild(div);
        });
    });
};

/**
 * 格式化请求头
 * @param {Array} headers - 请求头数组
 * @returns {string} 格式化后的请求头字符串
 */
function formatHeaders(headers) {
    if (!headers) return '';
    return headers.map(h => `${h.name}: ${h.value}`).join('\n');
}

/**
 * 重新发送请求
 * @param {HTMLElement} button - 触发重新发送的按钮
 * @param {string} url - 请求的URL
 * @param {string} method - 请求的方法
 */
async function resendRequest(button, url, method) {
    const requestContainer = button.closest('.request');
    const responseContainer = requestContainer.querySelector('.response-container');

    responseContainer.innerHTML = '<p>正在请求...</p>';

    try {
        const res = await fetch(url, {method});

        // 解析响应头
        const headers = {};
        res.headers.forEach((value, key) => {
            headers[key] = value;
        });

        // 获取 Content-Type
        const contentType = res.headers.get('content-type') || '';

        // 只读取一次 body
        const textBody = await res.text();

        let formattedBody;
        let isJson = false;
        let jsonBody;
        if (contentType.startsWith('image/')) {
            const imageUrl = URL.createObjectURL(new Blob([textBody], { type: contentType }));
            formattedBody = `<img src="${imageUrl}" style="max-width: 100%; height: auto;" />`;
        } else if (contentType.includes('application/json')) {

            try {
                jsonBody = JSON.parse(textBody);
                formattedBody = JSON.stringify(jsonBody, null, 2);
                isJson = true;
            } catch (e) {
                formattedBody = '无效的 JSON 数据\n' + textBody.slice(0, 10000);
            }
        } else if (contentType.includes('text/html')) {
            // 创建一个 Blob 存储 HTML 内容
            const htmlBlob = new Blob([textBody], {type: 'text/html'});
            const htmlUrl = URL.createObjectURL(htmlBlob);

            // 构建 iframe 展示区域
            formattedBody = `    <div style="margin-top: 10px; border: 1px solid #ccc;">
              <iframe 
                src="${htmlUrl}" 
                style="width: 100%; height: 300px; border: none;" 
                sandbox="allow-scripts allow-forms">
              </iframe>
            </div>
          `;
        } else if (contentType.includes('text/plain')) {
            formattedBody = `文本内容已截取前 1000 字符：\n${textBody.slice(0, 10000)}...`;
        } else {
            formattedBody = textBody;
        }

        // 判断是否需要截断
        const MAX_DISPLAY_LENGTH = 1000;
        const isTruncated = textBody.length > MAX_DISPLAY_LENGTH;

        // 构建 HTML 片段
        const truncatedMessage = isTruncated
            ? `<button class="toggle-full" onclick="toggleFullResponse(this, \`${encodeURIComponent(textBody)}\`, ${isJson})">展开全部</button><pre>${formattedBody}</pre>`
            : `<pre>${formattedBody}</pre>`;

        // 展示响应内容
        responseContainer.innerHTML = `
            <h4>响应头:</h4>
            <pre>${JSON.stringify(headers, null, 2)}</pre>
            <h4>响应体 (${contentType})：</h4>
            ${truncatedMessage}
        `;

        // 如果是 JSON 数据，添加导出按钮
        if (isJson && jsonBody && Array.isArray(jsonBody)) {
            const exportButton = document.createElement('button');
            exportButton.textContent = '导出为 Excel';
            exportButton.className = 'resend-button';
            exportButton.style.marginTop = '10px';

            exportButton.addEventListener('click', () => {
                exportToExcel(jsonBody);
            });

            responseContainer.appendChild(exportButton);
        }


    } catch (error) {
        responseContainer.innerHTML = `<p style="color:red;">请求失败: ${error.message}</p>`;
    }
}

/**
 * 展开或收起完整的响应内容
 * @param {HTMLElement} button - 触发展开的按钮
 * @param {string} fullText - 完整的响应文本
 * @param {boolean} isJson - 是否是 JSON 响应
 */
function toggleFullResponse(button, fullText, isJson) {
    const decodedText = decodeURIComponent(fullText);
    const parent = button.parentNode;
    const pre = document.createElement('pre');
    pre.style.marginTop = '10px';

    if (isJson) {
        try {
            const json = JSON.parse(decodedText);
            pre.textContent = JSON.stringify(json, null, 2);
        } catch (e) {
            pre.textContent = decodedText;
        }
    } else {
        pre.textContent = decodedText;
    }

    // 替换按钮和旧内容
    button.remove();
    const oldPre = parent.querySelector('pre');
    if (oldPre) oldPre.remove();
    parent.appendChild(pre);
}

/**
 * 将 JSON 数组导出为 Excel 文件
 * @param {Array} data - JSON 数组数据
 */
function exportToExcel(data) {
    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    XLSX.writeFile(wb, "data.xlsx");
}

